'use strict';

const Transaction = require('../../libs/DB/Transaction');
const operationRecord = require("../sys/operationRecordAction");
const moment = require("moment");
const _ = require("underscore");

module.exports = async function (params) {
    let transaction = new Transaction();
    try {
        await transaction.beginTransaction();
        if(params.costPlanId){
            let deviceResult = transaction.query(`SELECT count(*) AS count FROM device_file df INNER JOIN range_file rf ON rf.range_id = df.range_id AND rf.delete_sign = 1 AND rf.domain_id = ? WHERE df.cost_plan_id = ? AND df.delete_sign = 1 `,[params.userDomainId,params.costPlanId]);
            if(deviceResult[0].count > 0) throw {message:"此方案正在使用，无法修改"}
        }
        let isOverlap;
        if(params.costPlanType === 2){
            isOverlap = timeRangeOverlapJudge(params.costPlanColumnList);
        }else if(params.costPlanType === 3){
            isOverlap = valueOverlapJudge(params.costPlanColumnList);
        }
        if(isOverlap) throw { message:"范围区间存在重叠项" };
        let planObj ={
            cost_plan_name:params.costPlanName,
            domain_id:params.userDomainId,
            device_type:params.deviceType,
            cost_plan_type:params.costPlanType,
            cost_plan_settlement:params.isMonth ? params.costPlanSettlement : 32,
        }
        if(params.costPlanId) planObj.cost_plan_id = params.costPlanId;
        let insertResult = await transaction.query(`INSERT INTO cost_plan_file SET ? ON DUPLICATE KEY UPDATE ?`,[planObj,planObj]);
        let rangeList = params.costPlanColumnList;
        rangeList.push({
            costPlanColumnName:params.lostPriceName,
            price:params.lostPrice
        })
        for(const range of params.costPlanColumnList){
            let startRange = range.startRange ? range.startRange : null;
            let endRange = range.endRange ? range.endRange : null;
            if(parseInt(params.costPlanType) === 2 && startRange && endRange) {
                startRange = moment(startRange).format("HH:mm:ss");
                endRange = moment(endRange).format("HH:mm:ss");
            }
            let costColumnObj = {
                cost_plan_column_name:range.costPlanColumnName,
                start_range:startRange,
                end_range:endRange,
                type:range.type ? range.type : null,
                price:range.price,
                cost_plan_id:insertResult.insertId,
            }
            if(params.costPlanId){
                costColumnObj.cost_plan_id = params.costPlanId;
                await transaction.query(`DELETE FROM cost_plan_column WHERE cost_plan_id = ?`,[costColumnObj.cost_plan_id]);
            }
            await transaction.query(`INSERT INTO cost_plan_column SET ? `,[costColumnObj]);
        }
        await transaction.commit();
        await operationRecord(params);
        return {success: true};
    }catch (e){
        await transaction.rollback();
        return {success:false,message:e.message}
    }
};
function timeRangeOverlapJudge(ranges) {
    let timeListSort = _.sortBy(ranges,function (data){
        return moment(data.startRange).valueOf();
    })
    let isOverlap = false;
    if(timeListSort.length > 1){
        for(let i = 0;i<timeListSort.length;i++){
            let startTimeValue = moment(timeListSort[i].startRange).valueOf();
            let endTimeValue = moment(timeListSort[i].endRange).valueOf();
            if(endTimeValue < startTimeValue){
                endTimeValue =  moment(timeListSort[i].endRange).add(1,"day").valueOf();
            }
            if(i === timeListSort.length - 1 ){
                if(endTimeValue >= moment(timeListSort[0].startRange).valueOf() && endTimeValue <= moment(timeListSort[0].endRange).valueOf()){
                    isOverlap = true;
                    break;
                }
            }else{
                let nextStartTimeValue = moment(timeListSort[i + 1].startRange).valueOf();
                if(endTimeValue > nextStartTimeValue) {
                    isOverlap = true; // 如果找到相交的时间区间，返回 true
                    break;
                }
            }
        }
    }
    return isOverlap;
}
function valueOverlapJudge(ranges){
    let valueListSort = _.sortBy(ranges,function (data){
        return data.startRange;
    })
    let isOverlap = false;
    for(let i = 0;i<valueListSort.length;i++){
         let startRange = valueListSort[i].startRange;
         let endRange = valueListSort[i].endRange;
         if(endRange<startRange){
             isOverlap = true;
             break;
         }
         if(i<valueListSort.length - 1){
             let nextStartRange = valueListSort[i+1].startRange;
             if(nextStartRange < endRange){
                 isOverlap = true;
                 break;
             }
         }
    }
    return isOverlap;
}